<template>
  <div class="order-management-container">
    <h1>订单管理</h1>
    
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索订单号、客户名称..." 
          @input="handleSearch"
        />
        <button class="search-button">
          <i class="icon-search"></i>
        </button>
      </div>
      
      <div class="filter-buttons">
        <button @click="filterByStatus('all')" :class="{ active: currentFilter === 'all' }">全部</button>
        <button @click="filterByStatus('待付款')" :class="{ active: currentFilter === '待付款' }">待付款</button>
        <button @click="filterByStatus('待发货')" :class="{ active: currentFilter === '待发货' }">待发货</button>
        <button @click="filterByStatus('已发货')" :class="{ active: currentFilter === '已发货' }">已发货</button>
        <button @click="filterByStatus('已完成')" :class="{ active: currentFilter === '已完成' }">已完成</button>
        <button @click="filterByStatus('已取消')" :class="{ active: currentFilter === '已取消' }">已取消</button>
      </div>
      
      <div class="date-filter">
        <span>日期：</span>
        <input type="date" v-model="startDate" @change="handleDateFilter">
        <span>至</span>
        <input type="date" v-model="endDate" @change="handleDateFilter">
      </div>
    </div>
    
    <div class="orders-table">
      <table>
        <thead>
          <tr>
            <th>订单号</th>
            <th>客户名称</th>
            <th>下单时间</th>
            <th>商品数量</th>
            <th>订单金额</th>
            <th>支付方式</th>
            <th>订单状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in paginatedOrders" :key="order.id">
            <td>{{ order.id }}</td>
            <td>{{ order.customer }}</td>
            <td>{{ order.orderDate }}</td>
            <td>{{ order.itemCount }}</td>
            <td>¥{{ order.amount }}</td>
            <td>{{ order.paymentMethod }}</td>
            <td>
              <span :class="['status-badge', getStatusClass(order.status)]">
                {{ order.status }}
              </span>
            </td>
            <td class="actions">
              <button class="view-btn" @click="viewOrderDetails(order)">查看</button>
              <button class="edit-btn" @click="editOrder(order)">编辑</button>
              <button 
                v-if="order.status === '待发货'" 
                class="ship-btn" 
                @click="shipOrder(order)"
              >
                发货
              </button>
              <button 
                v-if="order.status === '待付款'" 
                class="cancel-btn" 
                @click="cancelOrder(order)"
              >
                取消
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <div class="pagination" v-if="totalPages > 1">
      <button v-for="page in totalPages" :key="page" @click="goToPage(page)" :class="{ active: currentPage === page }">{{ page }}</button>
    </div>
    
    <!-- 订单详情模态框 -->
    <div class="modal" v-if="showDetailsModal">
      <div class="modal-content modal-lg">
        <div class="modal-header">
          <h2>订单详情 - {{ currentOrder.id }}</h2>
          <button class="close-btn" @click="closeDetailsModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="order-info">
            <div class="info-section">
              <h3>基本信息</h3>
              <div class="info-row">
                <div class="info-label">订单号：</div>
                <div class="info-value">{{ currentOrder.id }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">下单时间：</div>
                <div class="info-value">{{ currentOrder.orderDate }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">订单状态：</div>
                <div class="info-value">
                  <span :class="['status-badge', getStatusClass(currentOrder.status)]">
                    {{ currentOrder.status }}
                  </span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-label">支付方式：</div>
                <div class="info-value">{{ currentOrder.paymentMethod }}</div>
              </div>
            </div>
            
            <div class="info-section">
              <h3>客户信息</h3>
              <div class="info-row">
                <div class="info-label">客户名称：</div>
                <div class="info-value">{{ currentOrder.customer }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">联系电话：</div>
                <div class="info-value">{{ currentOrder.phone }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">收货地址：</div>
                <div class="info-value">{{ currentOrder.address }}</div>
              </div>
            </div>
          </div>
          
          <div class="order-items">
            <h3>订单商品</h3>
            <table>
              <thead>
                <tr>
                  <th>商品编号</th>
                  <th>商品名称</th>
                  <th>规格</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>小计</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in currentOrder.items" :key="index">
                  <td>{{ item.code }}</td>
                  <td>{{ item.name }}</td>
                  <td>{{ item.spec }}</td>
                  <td>¥{{ item.price }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>¥{{ (item.price * item.quantity).toFixed(2) }}</td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="5" class="text-right">商品总额：</td>
                  <td>¥{{ currentOrder.amount }}</td>
                </tr>
                <tr>
                  <td colspan="5" class="text-right">运费：</td>
                  <td>¥{{ currentOrder.shipping || '0.00' }}</td>
                </tr>
                <tr>
                  <td colspan="5" class="text-right">订单总额：</td>
                  <td class="total-amount">¥{{ (parseFloat(currentOrder.amount) + parseFloat(currentOrder.shipping || 0)).toFixed(2) }}</td>
                </tr>
              </tfoot>
            </table>
          </div>
          
          <div class="order-logs" v-if="currentOrder.logs && currentOrder.logs.length">
            <h3>订单日志</h3>
            <div class="log-item" v-for="(log, index) in currentOrder.logs" :key="index">
              <div class="log-time">{{ log.time }}</div>
              <div class="log-content">{{ log.content }}</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeDetailsModal">关闭</button>
          <button 
            v-if="currentOrder.status === '待发货'" 
            class="ship-btn" 
            @click="shipOrder(currentOrder)"
          >
            发货
          </button>
          <button 
            v-if="currentOrder.status === '待付款'" 
            class="cancel-btn" 
            @click="cancelOrder(currentOrder)"
          >
            取消订单
          </button>
        </div>
      </div>
    </div>
    
    <!-- 编辑订单模态框 -->
    <div class="modal" v-if="showEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>编辑订单</h2>
          <button class="close-btn" @click="closeEditModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>订单状态</label>
            <select v-model="editingOrder.status">
              <option value="待付款">待付款</option>
              <option value="待发货">待发货</option>
              <option value="已发货">已发货</option>
              <option value="已完成">已完成</option>
              <option value="已取消">已取消</option>
            </select>
          </div>
          <div class="form-group">
            <label>客户名称</label>
            <input type="text" v-model="editingOrder.customer">
          </div>
          <div class="form-group">
            <label>联系电话</label>
            <input type="text" v-model="editingOrder.phone">
          </div>
          <div class="form-group">
            <label>收货地址</label>
            <textarea v-model="editingOrder.address"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button class="save-btn" @click="saveOrder">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderManagement',
  data() {
    return {
      orders: [
        {
          id: 'ORD20230625001',
          customer: '张三',
          orderDate: '2023-06-25 10:30',
          itemCount: 3,
          amount: '459.00',
          paymentMethod: '微信支付',
          status: '已完成',
          phone: '13800138001',
          address: '北京市朝阳区建国路88号',
          shipping: '10.00',
          items: [
          { code: 'P001', name: '男士休闲衬衫', spec: 'L码/蓝色', price: 129.00, quantity: 1 },
            { code: 'P004', name: '棒球帽', spec: '均码/红色', price: 89.00, quantity: 2 },
            { code: 'P005', name: '智能手表', spec: '黑色/防水', price: 899.00, quantity: 1 }
          ],
          logs: [
            { time: '2023-06-25 10:30', content: '用户下单' },
            { time: '2023-06-25 10:35', content: '用户支付完成' },
            { time: '2023-06-25 14:20', content: '商家发货' },
            { time: '2023-06-28 18:45', content: '用户确认收货' }
          ]
        },
        {
          id: 'ORD20230624005',
          customer: '李四',
          orderDate: '2023-06-24 15:45',
          itemCount: 2,
          amount: '3298.00',
          paymentMethod: '支付宝',
          status: '已发货',
          phone: '13800138002',
          address: '上海市浦东新区陆家嘴1号',
          shipping: '0.00',
          items: [
            { code: 'P006', name: '智能手机', spec: '128GB/黑色', price: 3999.00, quantity: 1 },
            { code: 'P009', name: '无线耳机', spec: '白色/降噪', price: 799.00, quantity: 1 }
          ],
          logs: [
            { time: '2023-06-24 15:45', content: '用户下单' },
            { time: '2023-06-24 15:50', content: '用户支付完成' },
            { time: '2023-06-25 09:30', content: '商家发货' }
          ]
        },
        {
          id: 'ORD20230624003',
          customer: '王五',
          orderDate: '2023-06-24 11:20',
          itemCount: 1,
          amount: '2599.00',
          paymentMethod: '银行卡',
          status: '待发货',
          phone: '13800138003',
          address: '广州市天河区体育西路123号',
          shipping: '15.00',
          items: [
            { code: 'P008', name: '平板电脑', spec: '64GB/银色', price: 2599.00, quantity: 1 }
          ],
          logs: [
            { time: '2023-06-24 11:20', content: '用户下单' },
            { time: '2023-06-24 11:25', content: '用户支付完成' }
          ]
        },
        {
          id: 'ORD20230623008',
          customer: '赵六',
          orderDate: '2023-06-23 16:30',
          itemCount: 3,
          amount: '1257.00',
          paymentMethod: '微信支付',
          status: '已完成',
          phone: '13800138004',
          address: '深圳市南山区科技园456号',
          shipping: '10.00',
          items: [
            { code: 'P002', name: '女士牛仔裤', spec: 'M码/黑色', price: 199.50, quantity: 2 },
            { code: 'P003', name: '运动跑鞋', spec: '42码/白色', price: 459.00, quantity: 1 },
            { code: 'P004', name: '棒球帽', spec: '均码/红色', price: 89.00, quantity: 1 }
          ],
          logs: [
            { time: '2023-06-23 16:30', content: '用户下单' },
            { time: '2023-06-23 16:35', content: '用户支付完成' },
            { time: '2023-06-24 10:15', content: '商家发货' },
            { time: '2023-06-26 14:20', content: '用户确认收货' }
          ]
        },
        {
          id: 'ORD20230623006',
          customer: '钱七',
          orderDate: '2023-06-23 14:15',
          itemCount: 1,
          amount: '3299.00',
          paymentMethod: '支付宝',
          status: '待付款',
          phone: '13800138005',
          address: '成都市锦江区红星路789号',
          shipping: '0.00',
          items: [
            { code: 'P010', name: '4K智能电视', spec: '55英寸', price: 3299.00, quantity: 1 }
          ],
          logs: [
            { time: '2023-06-23 14:15', content: '用户下单' }
          ]
        },
        {
          id: 'ORD20230622010',
          customer: '孙八',
          orderDate: '2023-06-22 09:45',
          itemCount: 2,
          amount: '3898.00',
          paymentMethod: '银行卡',
          status: '已取消',
          phone: '13800138006',
          address: '武汉市江汉区解放大道101号',
          shipping: '20.00',
          items: [
            { code: 'P011', name: '双门冰箱', spec: '218L/银色', price: 2199.00, quantity: 1 },
            { code: 'P013', name: '空调', spec: '1.5匹/变频', price: 2999.00, quantity: 1 }
          ],
          logs: [
            { time: '2023-06-22 09:45', content: '用户下单' },
            { time: '2023-06-22 09:50', content: '用户支付完成' },
            { time: '2023-06-22 14:30', content: '用户申请取消' },
            { time: '2023-06-22 16:15', content: '商家确认取消' },
            { time: '2023-06-22 16:20', content: '系统退款完成' }
          ]
        }
      ],
      currentPage: 1,
      itemsPerPage: 10,
      searchQuery: '',
      currentFilter: 'all',
      startDate: '',
      endDate: '',
      showDetailsModal: false,
      showEditModal: false,
      currentOrder: {},
      editingOrder: {}
    };
  },
  computed: {
    filteredOrders() {
      let result = this.orders;
      
      // 应用状态筛选
      if (this.currentFilter !== 'all') {
        result = result.filter(order => order.status === this.currentFilter);
      }
      
      // 应用日期筛选
      if (this.startDate && this.endDate) {
        const start = new Date(this.startDate);
        const end = new Date(this.endDate);
        end.setHours(23, 59, 59); // 设置为当天结束时间
        
        result = result.filter(order => {
          const orderDate = new Date(order.orderDate);
          return orderDate >= start && orderDate <= end;
        });
      }
      
      // 应用搜索筛选
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(order => 
          order.id.toLowerCase().includes(query) || 
          order.customer.toLowerCase().includes(query)
        );
      }
      
      return result;
    },
    paginatedOrders() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredOrders.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.filteredOrders.length / this.itemsPerPage);
    }
  },
  methods: {
    goToPage(page) {
      this.currentPage = page;
    },
    filterByStatus(status) {
      this.currentFilter = status;
      this.currentPage = 1; // 重置到第一页
    },
    handleSearch() {
      this.currentPage = 1; // 搜索时重置到第一页
    },
    handleDateFilter() {
      this.currentPage = 1; // 日期筛选时重置到第一页
    },
    viewOrderDetails(order) {
      this.currentOrder = { ...order };
      this.showDetailsModal = true;
    },
    closeDetailsModal() {
      this.showDetailsModal = false;
    },
    editOrder(order) {
      this.editingOrder = { ...order };
      this.showEditModal = true;
    },
    closeEditModal() {
      this.showEditModal = false;
    },
    saveOrder() {
      if (!this.editingOrder.customer || !this.editingOrder.phone) {
        alert('客户名称和联系电话不能为空');
        return;
      }
      
      const index = this.orders.findIndex(o => o.id === this.editingOrder.id);
      if (index !== -1) {
        // 记录状态变更
        if (this.orders[index].status !== this.editingOrder.status) {
          if (!this.editingOrder.logs) {
            this.editingOrder.logs = [];
          }
          
          const now = new Date();
          const timeStr = now.toISOString().replace('T', ' ').substring(0, 19);
          this.editingOrder.logs.push({
            time: timeStr,
            content: `订单状态从"${this.orders[index].status}"变更为"${this.editingOrder.status}"`
          });
        }
        
        this.orders[index] = { ...this.editingOrder };
        alert('订单信息已更新');
        this.closeEditModal();
      }
    },
    shipOrder(order) {
      if (confirm(`确定要为订单 ${order.id} 发货吗？`)) {
        const index = this.orders.findIndex(o => o.id === order.id);
        if (index !== -1) {
          this.orders[index].status = '已发货';
          
          if (!this.orders[index].logs) {
            this.orders[index].logs = [];
          }
          
          const now = new Date();
          const timeStr = now.toISOString().replace('T', ' ').substring(0, 19);
          this.orders[index].logs.push({
            time: timeStr,
            content: '商家发货'
          });
          
          alert('订单已标记为已发货');
          
          // 如果当前正在查看该订单详情，更新当前订单对象
          if (this.showDetailsModal && this.currentOrder.id === order.id) {
            this.currentOrder = { ...this.orders[index] };
          }
        }
      }
    },
    cancelOrder(order) {
      if (confirm(`确定要取消订单 ${order.id} 吗？`)) {
        const index = this.orders.findIndex(o => o.id === order.id);
        if (index !== -1) {
          this.orders[index].status = '已取消';
          
          if (!this.orders[index].logs) {
            this.orders[index].logs = [];
          }
          
          const now = new Date();
          const timeStr = now.toISOString().replace('T', ' ').substring(0, 19);
          this.orders[index].logs.push({
            time: timeStr,
            content: '订单已取消'
          });
          
          alert('订单已取消');
          
          // 如果当前正在查看该订单详情，更新当前订单对象
          if (this.showDetailsModal && this.currentOrder.id === order.id) {
            this.currentOrder = { ...this.orders[index] };
          }
        }
      }
    },
    getStatusClass(status) {
      const statusClassMap = {
        '待付款': 'status-pending',
        '待发货': 'status-paid',
        '已发货': 'status-shipped',
        '已完成': 'status-completed',
        '已取消': 'status-cancelled'
      };
      return statusClassMap[status] || '';
    }
  }
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 10px 40px 10px 15px;
  border: 1px solid #ddd;
  border-radius: 25px;
  font-size: 14px;
}

.search-button {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 18px;
  color: #666;
  cursor: pointer;
}

.icon-search:before {
  content: "🔍";
}

.filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-buttons button {
  padding: 8px 15px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.filter-buttons button.active {
  background-color: #4a90e2;
  color: white;
  border-color: #4a90e2;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-filter input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.orders-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f5f5f5;
  font-weight: bold;
}

tr:hover {
  background-color: #f9f9f9;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
}

.status-pending {
  background-color: #fff8e1;
  color: #ff8f00;
}

.status-paid {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-shipped {
  background-color: #e8f5e9;
  color: #388e3c;
}

.status-completed {
  background-color: #e0f2f1;
  color: #00796b;
}

.status-cancelled {
  background-color: #ffebee;
  color: #d32f2f;
}

.actions {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.actions button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.view-btn {
  background-color: #9e9e9e;
  color: white;
}

.edit-btn {
  background-color: #2196f3;
  color: white;
}

.ship-btn {
  background-color: #4caf50;
  color: white;
}

.cancel-btn {
  background-color: #f44336;
  color: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination button {
  margin: 0 5px;
  width: 36px;
  height: 36px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button.active {
  background-color: #4a90e2;
  color: white;
  border-color: #4a90e2;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.modal-content.modal-lg {
  width: 800px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 1;
}

.modal-header h2 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  position: sticky;
  bottom: 0;
  background-color: white;
  z-index: 1;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  min-height: 100px;
  resize: vertical;
}

/* 订单详情样式 */
.order-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.info-section {
  flex: 1;
  min-width: 300px;
}

.info-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
}

.info-label {
  width: 100px;
  color: #666;
}

.info-value {
  flex: 1;
}

.order-items {
  margin-bottom: 20px;
}

.order-items h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.text-right {
  text-align: right;
  font-weight: bold;
}

.total-amount {
  font-weight: bold;
  color: #f44336;
}

.order-logs {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.order-logs h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.log-item {
  display: flex;
  margin-bottom: 10px;
}

.log-time {
  width: 180px;
  color: #666;
}

.log-content {
  flex: 1;
}

@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-buttons {
    width: 100%;
    overflow-x: auto;
    padding-bottom: 10px;
  }
  
  .date-filter {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .info-row {
    flex-direction: column;
  }
  
  .info-label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>